﻿
Imports System.Threading
Imports osi.root.lock
Imports osi.root.utils

Public Class sync_pool_one_adapter(Of T)
    Inherits pool_one_adapter(Of T, isync_device_pool(Of T))

    Private ReadOnly finish_get_event As ManualResetEvent
    Private begin_get_event As singleentry

    Public Sub New(ByVal p As isync_device_pool(Of T))
        MyBase.New(p)
        finish_get_event = New ManualResetEvent(False)
    End Sub

    Protected Overloads Function [get](ByRef o As T) As Boolean
        While True
            o = [get]()
            If o Is Nothing Then
                finish_get_event.Reset()
                If begin_get_event.mark_in_use() Then
                    o = [get]()
                    If Not o Is Nothing OrElse
                       (p.sync_get(o) AndAlso Not o Is Nothing) Then
                        [set](o)
                        begin_get_event.release()
                        assert(finish_get_event.Set())
                        Return True
                    Else
                        Return False
                    End If
                Else
                    assert(finish_get_event.WaitOne())
                End If
            Else
                Return True
            End If
        End While
        Return assert(False)
    End Function

    Protected Overrides Sub Finalize()
        finish_get_event.Close()
        GC.KeepAlive(finish_get_event)
        MyBase.Finalize()
    End Sub
End Class
